<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace app\shop\api;

use app\common\api\BaseApi;
use app\shop\model\Coupon;
// use app\shop\api\CouponTplApi;
// use app\shop\model\VUserCoupon;
use app\system\api\MemberApi;
use app\admin\api\MessageApi;
use app\admin\model\Message;

class CouponApi extends BaseApi {

    /**
     * 注册送红包
     */
    const REG_ADD = "shop/CouponApi/reg_add";
    /**
     * 添加
     */
    const ADD = "shop/CouponApi/add";
    /**
     * 保存
     */
    const SAVE = "shop/CouponApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "shop/CouponApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "shop/CouponApi/delete";

    /**
     * 查询
     */
    const QUERY = "shop/CouponApi/query";
    /**
     * 查询
     */
    const API_QUERY = "shop/CouponApi/queryWithCount";

    /**
     * 查询一条数据
     */
    const GET_INFO = "shop/CouponApi/getInfo";
    /**
     * 包含红包模版信息的一条数据
     */
    const GET_INFO_WITH_EXTRA = "shop/CouponApi/getInfoWithExtra";

    /**
     * 不分页查询
     */
    const QUERY_WITH_TPL = "shop/CouponApi/queryWithTpl";
    const SEND_TO_USER = "shop/CouponApi/sendToUser";
    const USEFUL_COUNT = "shop/CouponApi/userfulCount";

    protected function _init(){
        $this->model = new Coupon();
    }

    public function queryWithTpl($uid,$is_use = 0,$is_expire = 0){
        $field = 'r.*,(r.get_time+r.expire_time) as expire,t.use_condition,t.dtree_type,d.name';
        $query = $this -> model->alias('r') -> join("left join itboye_coupon_tpl as t on r.tpl_id=t.id") -> join("common_datatree as d on d.id=t.dtree_type");

        $map = ['r.uid' => $uid];
        $is_use    = intval($is_use);
        $is_expire = intval($is_expire);
        if(in_array($is_use,[0,1])) $map['r.use_status'] = $is_use;
        if(0 === $is_expire) $map['_string'] = '(r.get_time+r.expire_time) > '.time();
        elseif(1 === $is_expire) $map['_string'] = '(r.get_time+r.expire_time) <='.time();
        $result = $query -> where($map) ->field($field) ->select();

        if(false === $result) return $this -> apiReturnErr($this -> model -> getDbError());
        return $this -> apiReturnSuc($result);

    }
    /**
     * 发送给用户优惠券，可指定面额和时间
     * 若有消息推送 最好放外面 适应业务逻辑
     * rainbow - boye010@163.com
     * @param  [type]  $uid         [description]
     * @param  [type]  $tpl_id      [description]
     * @param  string  $notes       [description]
     * @param  integer $money       面额,0将使用模板面额
     * @param  integer $expire_time 时限,0将使用模板时限
     * @param  boolean $push        是否推送
     * @return array                api-Return
     */
    public function sendToUser($uid,$tpl_id,$notes='',$money=0,$expire_time=0,$push=false){

        $r = apiCall(MemberApi::GET_INFO,[['uid'=>$uid]]);
        if(!$r['status']) return $this->apiReturnErr($r['info']);
        if(empty($r['info'])) return $this->apiReturnErr('uid错误：'.$uid);

        $money = floatval($money);
        $expire_time = intval($expire_time);
        if($money<0 || $expire_time<0) return $this->apiReturnErr('参数错误：'.$money.'-'.$expire_time);

        $r = apiCall(CouponTplApi::GET_INFO,[['id'=>$tpl_id]]);
        if($r['status']){
            if(empty($r['info'])) return $this->apiReturnErr('优惠券模板错误'.$tpl_id);
            $money = $money ? $money : $r['info']['money'];
            $expire_time = $expire_time ? $expire_time : $r['info']['expire_time'];
        }else{
            return $this -> apiReturnErr($r['info']);
        }

        $entity = [
            'notes'       =>$notes,
            'uid'         =>$uid,
            'get_time'    =>time(),
            'use_status'  =>Coupon::NOT_USE,
            'tpl_id'      =>$tpl_id,
            'money'       =>$money,
            'expire_time' =>$expire_time,
        ];
        $r = $this->add($entity);
        if(!$r['status']) return $r;
        if($push){
            $entity = [
                'from_id' =>0,
                'title'   =>Message::MESSAGE_SYSTEM,
                'content' =>'您获得一张'.$money.'元优惠券',
                'summary' =>'您获得一张'.$money.'元优惠券',
                'extra'   =>'', //消息记录中的
            ];
            $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_SYSTEM_ACTIVITY,'extra'=>[]]; //推送参数
            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_SYSTEM,$entity,$uid,false,$after_open]);
            if(!$r['status']) return $this->apiReturnSuc($r['info']);
            return $this->apiReturnSuc('发送成功');
        }else{
            return $this->apiReturnSuc('发送成功');
        }
    }

}